use std::io::Write;
use crate::model::{Config, MysqlConfig};
use tool::tool_convert;
use tool::tool_io;
use tool::tool_json;
use tool::tool_result::Error;

static CONFIG_PATH: &str = "./config.json";

pub fn get_config() -> Result<Config, Error> {
    if !tool_io::exist_dir_for_file(CONFIG_PATH.to_string()) {
        init_config()?;
    }
    let config_bytes = tool_io::read_file(CONFIG_PATH.to_string())?;
    let config_str = tool_convert::bytes_to_string_utf8(&config_bytes);
    let config = match tool_json::deserialize::<Config>(config_str){
        Ok(e) => e,
        Err(e) => return Err(Error::new(format!("解析config.json错误，检查格式是否正确（{}）",e.err.unwrap())))
    };
    check_config(&config)?;
    Ok(config)
}

fn init_config() -> Result<(), Error> {
    let config = Config::new();
    let config_str = tool_json::serialize_pretty(config)?;
    let mut file = tool_io::create_file_and_return(CONFIG_PATH.to_string())?;
    match file.write_all(&tool_convert::string_to_bytes(config_str.as_str())) {
        Ok(_) => Ok(()),
        Err(e) => Err(Error::new(e.to_string())),
    }
}

fn check_config(config: &Config) -> Result<(), Error> {
    check_config_mysql(&config.mysql_list)
}

fn check_config_mysql(config: &Vec<MysqlConfig>) -> Result<(), Error> {
    for mysql_config in config {
        if mysql_config.database == "" || mysql_config.user == "" || mysql_config.password == "" {
            return Err(Error::new("mysql配置不完整"));
        }
        if mysql_config.auto_backup_time != "" {
            mysql_config.get_auto_backup_time()?;
        }
        if mysql_config.is_docker&&mysql_config.docker_container_name==""{
            return Err(Error::new("docker容器名称不能为空"));
        }
    }
    Ok(())
}
